package com.basic.modules.ykf.controller;

import java.util.Arrays;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.basic.common.annotation.StringTrim;
import com.basic.common.exception.RRException;
import com.basic.common.utils.ParamsModel;
import com.basic.common.validator.ValidatorUtils;

import com.basic.modules.ykf.model.YkfCusSerScoreModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.basic.modules.ykf.entity.YkfCusSerScoreEntity;
import com.basic.modules.ykf.service.YkfCusSerScoreService;
import com.basic.common.utils.PageUtils;
import com.basic.common.utils.R;



/**
 * 用户分数
 *
 * @author maoheng
 * @email 15738859597@163.com
 * @date 2024-05-13 15:55:57
 */
@RestController
@RequestMapping("ykf/cusSerScore")
public class YkfCusSerScoreController {

    @Autowired
    private YkfCusSerScoreService ykfCusSerScoreService;

    /**
     * 列表-分页
     */
    @StringTrim
    @PostMapping("/page")
    public R list(@RequestBody ParamsModel<YkfCusSerScoreModel> params){
        PageUtils page = ykfCusSerScoreService.queryPage(params);
        return R.ok(page);
    }

    /**
     * 信息
     */
    @PostMapping("/info")
    public R info(@RequestBody YkfCusSerScoreEntity params){
        if (ObjectUtil.isEmpty(params) || ObjectUtil.isEmpty(params.getScoreId())) {
            throw new RRException("参数缺失");
        }
        return R.ok(ykfCusSerScoreService.getById(params.getScoreId()));
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    public R save(@RequestBody YkfCusSerScoreEntity ykfCusSerScore){
        ValidatorUtils.validateEntity(ykfCusSerScore);
        //校验存在
        validCusSer(ykfCusSerScore);
		ykfCusSerScoreService.save(ykfCusSerScore);
        return R.ok();
    }

    private void validCusSer(YkfCusSerScoreEntity ykfCusSerScore) {
        QueryWrapper<YkfCusSerScoreEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(YkfCusSerScoreEntity::getMonth, ykfCusSerScore.getMonth())
                .eq(YkfCusSerScoreEntity::getUserId, ykfCusSerScore.getUserId());
        if (ObjectUtil.isNotEmpty(ykfCusSerScore.getScoreId())) {
            queryWrapper.lambda().ne(YkfCusSerScoreEntity::getScoreId, ykfCusSerScore.getScoreId());
        }
        if (ykfCusSerScoreService.count(queryWrapper) > 0) {
            throw new RRException("该用户本月份已有分数，请检查");
        }
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    public R update(@RequestBody YkfCusSerScoreEntity ykfCusSerScore){
        ValidatorUtils.validateEntity(ykfCusSerScore);
        validCusSer(ykfCusSerScore);
		ykfCusSerScoreService.updateById(ykfCusSerScore);
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] scoreIds){
		ykfCusSerScoreService.removeByIds(Arrays.asList(scoreIds));
        return R.ok();
    }

}
